<template>
  <div class="container">
    <h2>用户管理</h2>
    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>

    <!-- 用户表格 -->
    <el-table :data="users" border style="margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="password" label="密码"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="role" label="角色">
        <template #default="scope">{{ scope.row.role === 0 ? '普通用户' : '管理员' }}</template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role">
            <el-option label="普通用户" value="0"></el-option>
            <el-option label="管理员" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '../utils/request'
import { ElMessage } from 'element-plus'

// 数据初始化
const users = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加用户')
const form = ref({ id: null, username: '', password: '', phone: '', role: 0 })

// 获取所有用户
const getUsers = async () => {
  const res = await request.get('/users')
  users.value = res.data.data
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  form.value = { ...row }
  dialogVisible.value = true
}

// 保存用户（添加/编辑）
const saveForm = async () => {
  if (form.value.id) {
    await request.put('/users', form.value)
    ElMessage.success('更新成功')
  } else {
    await request.post('/users', form.value)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  getUsers()
}

// 删除用户
const handleDelete = async (id) => {
  await request.delete(`/users/${id}`)
  ElMessage.success('删除成功')
  getUsers()
}

// 页面加载时获取数据
onMounted(getUsers)
</script>